using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;

namespace Framework.Library.Core.Utils.Web.Modules
{
    public class AccessDeniedRedirectModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.EndRequest += EndRequest;
        }

        #endregion

        private void EndRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication) sender;
            HttpContext context = application.Context;
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            bool redirectAccessDenied = false;

            switch (context.Response.StatusCode)
            {
                case 401:
                    if (context.Handler is Page && request.IsAuthenticated)
                        redirectAccessDenied = true;
                    break;
                case 302:
                    if (request.IsAuthenticated)
                    {
                        bool hasAccess = UrlAuthorizationModule.CheckUrlAccessForPrincipal(request.Url.LocalPath,
                                                                                           context.User,
                                                                                           request.RequestType);

                        if (!hasAccess)
                        {
                            string redirectUrl = response.RedirectLocation.ToUpperInvariant();
                            string loginUrl = FormsAuthentication.LoginUrl.ToUpperInvariant();

                            redirectAccessDenied = redirectUrl.StartsWith(loginUrl);
                        }
                    }
                    break;
            }

            if (redirectAccessDenied)
                response.Redirect("~/AccessDenied.aspx", true);
        }
    }
}